package com.cat.app

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.usb.UsbDevice.getDeviceId
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.telephony.SubscriptionInfo
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat.startActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"

    internal object settingClickListener : View.OnClickListener {
        override fun onClick(v: View?) {

            val intent = Intent()
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            intent.data = Uri.parse("package:${v?.context?.packageName}")
            v?.context?.startActivity(intent)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)



        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_STATE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 1200)
        } else getDeviceIds()


    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 1200) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getDeviceIds()
            } else {
                deviceNumber.text = "权限被拒绝，-_-||,请到设置中授予权限吧,点我设置"
                deviceNumber.setOnClickListener(settingClickListener)
            }
        }
    }


    @SuppressLint("MissingPermission", "SetTextI18n")
    fun getDeviceIds() {

        var deviceId: String? = null
        var imei: String? = null
        var imei1: String? = null
        var imei2: String? = null
        var meid: String? = null
        var androidId: String? = null
        var telecomManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

        var activeSimSlotInfoText = StringBuffer()


        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {//26 deprecated deviceid
            imei = telecomManager.imei
            imei1 = telecomManager.getImei(0)
            imei2 = telecomManager.getImei(1)
            meid = telecomManager.meid
        }

        androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)

        deviceId = telecomManager.deviceId

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            val subscriptionManager = getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
            val activeSubscriptionInfoList: List<SubscriptionInfo>? = subscriptionManager.activeSubscriptionInfoList
            activeSubscriptionInfoList?.forEach {
                activeSimSlotInfoText.append("卡槽 ${it.simSlotIndex} 有sim卡插入")
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                    activeSimSlotInfoText.append("${telecomManager.getImei(it.simSlotIndex)}\n")
            }

        }


        val s = "您的设备信息 \n 卡槽数：${telecomManager.phoneCount}\n" +
                "运营商类型：${getPhoneTypeString(telecomManager.phoneType)}\n" +
                "AndroidVersion: ${Build.VERSION.SDK_INT}\n"+
                "deviceId  :$deviceId \n" +
                "默认imei: $imei\n" +
                "imei1      : $imei1 \n" +
                "imei2      : $imei2 \n" +
                "meid       : $meid\n" +
                "ANDROID_ID: $androidId" +
                "$activeSimSlotInfoText"
        Log.i(TAG, "getDeviceIds: $s")
        deviceNumber.text =
            s

    }

    private fun getPhoneTypeString(phoneType: Int): String {
        return when (phoneType) {
            TelephonyManager.PHONE_TYPE_CDMA -> "电信"
            TelephonyManager.PHONE_TYPE_GSM -> "移动"
            TelephonyManager.PHONE_TYPE_NONE -> "未知"
            else -> "未知1"
        }
    }
}
